package org.dwell.vertx3.demos.tcp;

import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Verticle;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;

import java.lang.management.BufferPoolMXBean;

/**
 * Created by JianGuo on 2016/1/15.
 */
public class NetServerVerticle implements Verticle {

    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        vertx.deployVerticle(new NetServerVerticle());
    }

    private Vertx vertx;

    @Override
    public Vertx getVertx() {
        return vertx;
    }

    @Override
    public void init(Vertx vertx, Context context) {
        this.vertx = vertx;
    }

    @Override
    public void start(Future<Void> voidFuture) throws Exception {
        NetServerOptions options = new NetServerOptions().setPort(4321);
        NetServer server = vertx.createNetServer(options);


        //当有客户端连接进入时触发
        server.connectHandler(socket -> {
            //Handle the connection in here

            //Reading data from the socket
            socket.handler(buffer -> {
                System.out.println("I received some bytes: " + buffer.length());
            });

            //Writing data to a socket
            //回写操作是异步的，所以可能不会立即返回
            Buffer buffer = Buffer.buffer().appendFloat(12.34f).appendInt(123);
            socket.write(buffer);       //默认是utf-8编码

            //如果需要用指定的编码，如下
            socket.write("hello jange", "UTF-16");


            //关闭连接，当有客户端的连接和服务端断开后，就会进入这个方法
            socket.closeHandler(v -> {
                System.out.println("The socket has been closed!");
            });

            //处理异常
            //比如，客户端不调用close socket方法，强制关闭连接，就会触发exception
            socket.exceptionHandler(t -> {
                t.printStackTrace();
                System.out.println("The socket exception is " + t.getMessage());
            });

            System.out.println(socket.remoteAddress());

            System.out.println(socket.localAddress());

        });

        //关闭一个TCP服务器
        //当verticle被undeploy后，关联的Server也会自动关闭
//        server.close(res -> {
//            if (res.succeeded()) {
//                System.out.println("Server is now closed");
//            } else {
//                System.out.println("close failed");
//            }
//        });

        server.listen(res -> {
            if(res.succeeded()) {
                System.out.println("Server is now listening...");
            } else {
                System.out.println("Failed to bind!");
            }
        });
    }

    @Override
    public void stop(Future<Void> voidFuture) throws Exception {

    }
}
